//
//  SetView.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2024/12/26.
//

import SwiftUI
import Kingfisher
import PhotosUI

//ai 人设编辑界面
struct AiRoleView: View {
    @StateObject var viewModel = AiRoleViewModel()
    @State private var selectedItem: PhotosPickerItem?
    @State private var selectedImage: UIImage?
    @State private var selectedChatItem: PhotosPickerItem?
    @State private var selectedChatImage: UIImage?
    @State private var selectedDiaryItem: PhotosPickerItem?
    @State private var selectedDiaryImage: UIImage?
    @State private var showUploadImage = false
    @State var image: UIImage?
    @State private var name: String = ""
    @State private var name2: String = ""
    @State private var desc: String = ""
    @State private var desc2: String = ""
    @State private var descChat: String = ""
    @State private var avatar: String = ""
    @State private var bgChat: String = ""
    @State private var bgDiary: String = ""
    @State private var genderOptions = [PickItem(id: "0", name: "男"), PickItem(id: "1", name: "女")]
    @State var selectSexId = "0"
    @State var sexName = ""
    @State var voiceName = ""
    @FocusState private var isFocusedName: Bool
    @FocusState private var isFocusedName2: Bool
    @FocusState private var isFocusedDesc: Bool
    @FocusState private var isFocusedDesc2: Bool
    @FocusState private var isFocusedDescChat: Bool
    @State private var showVoice = false
    @State private var isAdd = true
    var bean : AiRoleBean
    
    init(bean: AiRoleBean? = nil) {
        self.bean = bean ?? AiRoleBean()
    }

    var body: some View {
        ScrollView(.vertical) {
            VStack(alignment: .leading) {
                Text("头像")
                    .font(.system(size: 14))
                    .foregroundStyle(.bgNormalText2)
                PhotosPicker(selection: $selectedItem, matching: .images) {
                    avatarView
                }
                HStack{
                    VStack(alignment: .leading){
                        Text("名字")
                            .font(.system(size: 14))
                            .foregroundStyle(.bgNormalText2)
                            .padding(.top,20)
                        TextField("名字", text: $name)
                            .font(.system(size: 12))
                            .foregroundColor(.bgItemTitle)
                            .textFieldStyle(PlainTextFieldStyle())
                            .focused($isFocusedName)
                            .padding(10)
                            .background(.bgChat)
                            .clipShape(RoundedRectangle(cornerRadius: 8))
                            .frame(width: 100)
                    }
                    VStack(alignment: .leading){
                        Text("称呼")
                            .font(.system(size: 14))
                            .foregroundStyle(.bgNormalText2)
                            .padding(.top,20)
                        TextField("称呼", text: $name2)
                            .font(.system(size: 12))
                            .foregroundColor(.bgItemTitle)
                            .textFieldStyle(PlainTextFieldStyle())
                            .focused($isFocusedName2)
                            .padding(10)
                            .background(.bgChat)
                            .clipShape(RoundedRectangle(cornerRadius: 8))
                            .frame(width: 100)
                    }.padding(.leading, 50)
                }
                HStack {
                    Text("性别")
                        .font(.system(size: 14))
                        .foregroundStyle(.bgNormalText2)
                    Text(!sexName.isEmpty ? sexName : "未知")
                        .font(.system(size: 12))
                        .foregroundStyle(.bgNormalText4)
                }.padding(.top,20)
                    .contentShape(Rectangle())
                    .onTapGesture {
                        clearFocused()
                        SwiftEntryKitWrapper.showBottomPopup { dismiss in
                            PickerView(title:"请选择性别",options:genderOptions,selectId:$selectSexId) {
                                let name = genderOptions.first(where: {selectSexId == $0.id})?.name
                                showLog("selectSexId:\(selectSexId)")
                                sexName = name ?? "未知"
                                dismiss()
                            }
                        }
                    }
                HStack {
                    Text("音色")
                        .font(.system(size: 14))
                        .foregroundStyle(.bgNormalText2)
                    Text(!voiceName.isEmpty ? voiceName : "点击选择音色")
                        .font(.system(size: 12))
                        .foregroundStyle(.bgNormalText4)
                }.padding(.top,20)
                    .contentShape(Rectangle())
                    .onTapGesture {
                        showVoice.toggle()
                    }
                HStack(spacing: 3) {
                    Text("聊天背景")
                        .font(.system(size: 14))
                        .foregroundStyle(.bgNormalText2)
                    Image(.appIconVip)
                        .resizable()
                        .frame(width: 15,height: 15)
                    PhotosPicker(selection: $selectedChatItem, matching: .images) {
                        bgChatView
                    }.padding(.leading,10)
                    Spacer()
                }.padding(.top,20)
                    .frame(maxWidth: .infinity)
                    .contentShape(Rectangle())
                    .onTapGesture {
                        showVoice.toggle()
                    }
                HStack(spacing: 3) {
                    Text("日记背景")
                        .font(.system(size: 14))
                        .foregroundStyle(.bgNormalText2)
                    Image(.appIconVip)
                        .resizable()
                        .frame(width: 15,height: 15)
                    PhotosPicker(selection: $selectedDiaryItem, matching: .images) {
                        bgDiaryView
                    }.padding(.leading,10)
                    Spacer()
                }.padding(.top,20)
                    .frame(maxWidth: .infinity)
                    .contentShape(Rectangle())
                    .onTapGesture {
                        showVoice.toggle()
                    }
                Text("描述")
                    .font(.system(size: 14))
                    .foregroundStyle(.bgNormalText2)
                    .padding(.top,20)
                ZStack(alignment: .topLeading) {
                    if desc.isEmpty {
                        Text(configManager.getConfig().aiChat.aiHint2 ?? "")
                            .font(.system(size: 12))
                            .foregroundColor(.bgHint)
                    }
                    TextEditor(text: $desc)
                        .font(.system(size: 12))
                        .foregroundColor(.bgItemTitle)
                        .textFieldStyle(PlainTextFieldStyle())
                        .focused($isFocusedDesc)
                        .scrollContentBackground(.hidden)
                        .padding(.top, -8) // 抵消默认顶部间距
                        .padding(.leading, -5) // 抵消默认左侧间距
                        .onChange(of: desc2) { newValue in
                            let maxLength = configManager.getConfig().aiChat.aiRoleMaxLength ?? 1000
                            if newValue.count > maxLength {
                                // 保留前1000个字符，避免超出
                                desc = String(newValue.prefix(maxLength))
                                showToast("字数已超出限制")
                            }
                        }
                    
                }.padding(10)
                    .frame(height: 100)
                    .frame(maxWidth: .infinity)
                    .background(.bgChat)
                    .clipShape(RoundedRectangle(cornerRadius: 8))
                Text("关于我的描述")
                    .font(.system(size: 14))
                    .foregroundStyle(.bgNormalText2)
                    .padding(.top,20)
                ZStack(alignment: .topLeading) {
                    if desc2.isEmpty {
                        Text("可以在这边填写自己的信息或者你们的故事\n字数限制1000")
                            .font(.system(size: 12))
                            .foregroundColor(.bgHint)
                    }
                    TextEditor(text: $desc2)
                        .font(.system(size: 12))
                        .foregroundColor(.bgItemTitle)
                        .textFieldStyle(PlainTextFieldStyle())
                        .focused($isFocusedDesc2)
                        .scrollContentBackground(.hidden)
                        .padding(.top, -8) // 抵消默认顶部间距
                        .padding(.leading, -5) // 抵消默认左侧间距
                        .onChange(of: desc2) { newValue in
                            if newValue.count > 1000 {
                                // 保留前1000个字符，避免超出
                                desc2 = String(newValue.prefix(1000))
                                showToast("字数限制1000")
                            }
                        }
                    
                }.padding(10)
                    .frame(height: 100)
                    .frame(maxWidth: .infinity)
                    .background(.bgChat)
                    .clipShape(RoundedRectangle(cornerRadius: 8))
                HStack(spacing: 0) {
                    Text("聊天回复规则")
                        .font(.system(size: 14))
                        .foregroundStyle(.bgNormalText2)
                    Text("(非必填)")
                        .font(.system(size: 12))
                        .foregroundStyle(.bgNormalText4)
                    Spacer()
                    if let chatTemplate = AiDescribeManager.shared.getConfig().chatTemplate, chatTemplate.isEmpty == false {
                        Text("使用模板")
                            .font(.system(size: 14))
                            .foregroundStyle(themeManager.themeColor)
                            .onTapGesture {
                                descChat = chatTemplate
                            }
                    }
                }.padding(.top,20)
                ZStack(alignment: .topLeading) {
                    if descChat.isEmpty {
                        Text(configManager.getConfig().aiChat.aiHintChat ?? "")
                            .font(.system(size: 12))
                            .foregroundColor(.bgHint)
                    }
                    TextEditor(text: $descChat)
                        .font(.system(size: 12))
                        .foregroundColor(.bgItemTitle)
                        .textFieldStyle(PlainTextFieldStyle())
                        .focused($isFocusedDescChat)
                        .scrollContentBackground(.hidden)
                        .padding(.top, -8) // 抵消默认顶部间距
                        .padding(.leading, -5) // 抵消默认左侧间距
                        .onChange(of: descChat) { newValue in
                            if newValue.count > 1000 {
                                // 保留前1000个字符，避免超出
                                descChat = String(newValue.prefix(1000))
                                showToast("字数限制1000")
                            }
                        }
                    
                }.padding(10)
                    .frame(height: 150)
                    .frame(maxWidth: .infinity)
                    .background(.bgChat)
                    .clipShape(RoundedRectangle(cornerRadius: 8))
                Spacer()
            }
        }.padding()
            .frame(maxWidth: .infinity, alignment: .leading)
            .navigationTitle(isAdd ? "创建心灵" :"修改心灵")
            .background(.bgWhite)
            .toolbar {
                Text("保存")
                    .foregroundColor(themeManager.themeColor)
                    .font(.system(size: 12))
                    .padding(.horizontal,10)
                    .padding(.vertical,7)
                    .cornerRadius(8)
                    .contentShape(Rectangle())
                    .onTapGesture {
                        clearFocused()
                        bean.name = name
                        bean.name2 = name2
                        bean.sexName = sexName
                        bean.describe = desc
                        bean.describe2 = desc2
                        bean.describeChat = descChat
                        viewModel.doSave(bean: bean, image: selectedImage,bgChat: selectedChatImage,bgDiary: selectedDiaryImage, isAdd: isAdd)
                    }
            }
            .sheet(isPresented: $showVoice) {
                //语音选择试图
                AiVoiceChooseView(choose: true) { aiVoiceBean in
                    aiVoiceBean.voiceHex = nil //hex需要置空，文本很大，并且没有用
                    bean.voice = aiVoiceBean
                    voiceName = bean.voice?.name ?? ""
                    showVoice = false
                }.presentationDragIndicator(.visible)
            }.onAppear{
                name = bean.name ?? ""
                name2 = bean.name2 ?? ""
                sexName = bean.sexName ?? ""
                desc = bean.describe ?? ""
                desc2 = bean.describe2 ?? ""
                descChat = bean.describeChat ?? ""
                avatar = bean.avatar.formatCdn()
                bgChat = bean.chatBg.formatCdn()
                bgDiary = bean.diaryBg.formatCdn()
                voiceName = bean.voice?.name ?? ""
                isAdd = (bean.objectId ?? "").isEmpty == true
                if(bean.isSystem == true) {
                    showToast("系统角色无法查看")
                    pathManager.back()
                }
            }
    }
    
    func clearFocused() {
        isFocusedName = false
        isFocusedName2 = false
        isFocusedDesc = false
        isFocusedDesc2 = false
        isFocusedDescChat = false
    }
}

/**
 *  用户信息头像
 */
extension AiRoleView{
    
    var avatarView: some View {
        HStack() {
            if let image = selectedImage {
                Image(uiImage: image)
                    .resizable()
                    .scaledToFill()
                    .background(.bgChat)
                    .clipShape(Circle())
                    .frame(width: 40,height: 40)
            } else {
                KFImage(URL(string: avatar))
                    .resizable()
                    .placeholder{
                        Image(.appIconLogo)
                            .resizable()
                            .scaledToFill()
                            .clipShape(Circle())
                    }
                    .scaledToFill()
                    .background(.bgChat)
                    .clipShape(Circle())
                    .frame(width: 40,height: 40)
            }
        }
        .onChange(of: selectedItem) { newItem in
            guard let newItem = newItem else {return}
            Task{
                if let data = try? await newItem.loadTransferable(type: Data.self) {
                    selectedImage = UIImage(data: data)
//                    await MainActor.run {
//                        if let uiImage = selectedImage {
//                            //                                viewModel.upload(image: uiImage)
//                        }
//                    }
                }
            }
        }
    }
    
    var bgChatView: some View {
        HStack() {
            if let image = selectedChatImage {
                ZStack(alignment:.topTrailing) {
                    Image(uiImage: image)
                        .resizable()
                        .scaledToFill()
                        .background(.bgChat)
                        .clipShape(RoundedRectangle(cornerRadius: 5))
                        .frame(width: 30)
                        .frame(minHeight: 30)
                    Image(.appIconImageDel)
                        .resizable()
                        .frame(width: 13,height: 13)
                        .contentShape(Rectangle())
                        .onTapGesture {
                            selectedChatImage = nil
                        }
                }
            } else {
                ZStack(alignment:.topTrailing) {
                    KFImage(URL(string: bgChat))
                        .resizable()
                        .scaledToFill()
                        .background(.bgChat)
                        .clipShape(RoundedRectangle(cornerRadius: 5))
                        .frame(width: 30)
                        .frame(minHeight: 30)
                    if bgChat.isEmpty == false {
                        Image(.appIconImageDel)
                            .resizable()
                            .frame(width: 13,height: 13)
                            .contentShape(Rectangle())
                            .onTapGesture {
                                viewModel.delChatBg = bean.chatBg
                                bean.chatBg = ""
                                bgChat = ""
                            }
                    }
                    
                }
            }
        }
        .onChange(of: selectedChatItem) { newItem in
            guard let newItem = newItem else {return}
            Task{
                if let data = try? await newItem.loadTransferable(type: Data.self) {
                    if !userManager.isVip() {
                        showToast("聊天背景 功能是Pro专享")
                        return
                    }
                    selectedChatImage = UIImage(data: data)
//                    await MainActor.run {
//                        if let uiImage = selectedImage {
//                            //                                viewModel.upload(image: uiImage)
//                        }
//                    }
                }
            }
        }
    }
    
    var bgDiaryView: some View {
        HStack() {
            if let image = selectedDiaryImage {
                ZStack(alignment:.topTrailing) {
                    Image(uiImage: image)
                        .resizable()
                        .scaledToFill()
                        .background(.bgChat)
                        .clipShape(RoundedRectangle(cornerRadius: 5))
                        .frame(width: 30)
                        .frame(minHeight: 30)
                    Image(.appIconImageDel)
                        .resizable()
                        .frame(width: 13,height: 13)
                        .contentShape(Rectangle())
                        .onTapGesture {
                            selectedDiaryImage = nil
                        }
                }
            } else {
                ZStack(alignment:.topTrailing) {
                    KFImage(URL(string: bgDiary))
                        .resizable()
                        .scaledToFill()
                        .background(.bgChat)
                        .clipShape(RoundedRectangle(cornerRadius: 5))
                        .frame(width: 30)
                        .frame(minHeight: 30)
                    if bgDiary.isEmpty == false {
                        Image(.appIconImageDel)
                            .resizable()
                            .frame(width: 13,height: 13)
                            .contentShape(Rectangle())
                            .onTapGesture {
                                viewModel.delDiaryBg = bean.diaryBg
                                bean.diaryBg = ""
                                bgDiary = ""
                            }
                    }
                    
                }
            }
        }
        .onChange(of: selectedDiaryItem) { newItem in
            guard let newItem = newItem else {return}
            Task{
                if let data = try? await newItem.loadTransferable(type: Data.self) {
                    if !userManager.isVip() {
                        showToast("日记背景 功能是Pro专享")
                        return
                    }
                    selectedDiaryImage = UIImage(data: data)
//                    await MainActor.run {
//                        if let uiImage = selectedImage {
//                            //                                viewModel.upload(image: uiImage)
//                        }
//                    }
                }
            }
        }
    }
}
//#Preview {
//    SetView()
//}


//定义预览提供者
struct AiRoleView_Previews: PreviewProvider {
    static var previews: some View {
        //使用预览共享配置
        configurePreviewEnvironment(for: AiRoleView(bean: nil))
    }
}
